<!--suppress ALL -->
<script setup>
import {Plus} from "@element-plus/icons-vue";

const editHandle = () => {
  isEditVisible.value = !isEditVisible.value;
}

import {onMounted, ref,defineEmits} from 'vue';
import axios from 'axios';
import {ElMessage} from "element-plus";

const isEditVisible = ref(false);
const username = ref('Aprillll');
const email = ref('1613348797@qq.com');
const password = ref('••••••••');
const Contact = ref('asuweijun');
const radio = ref(null)
const imageUrl = ref('');
const formData = new FormData();
const image = ref(null);
const recName = ref(null);
const recContact = ref(null);
const recContactType = ref(null);
const ifChange = ref(false);
const ifModified = ref(false);
defineEmits(['update'])
onMounted(() => {
  const userData = JSON.parse(sessionStorage.getItem('token'));
  axios.defaults.headers.common['Authorization'] = `${userData.token}`;
  // 获取个人信息
  const response = axios.get('http://localhost:8080/users/' + userData.userID);
  response.then((result) => {
    username.value = result.data.UName
    recName.value = result.data.UName
    email.value = result.data.Email
    Contact.value = result.data.Contact
    recContact.value = result.data.Contact
    if (result.data.ContactType !== '') {
      radio.value = Number(result.data.ContactType)
      recContactType.value = Number(result.data.ContactType)
    } else {
      radio.value = '';
    }
    imageUrl.value = result.data.ProfilePhoto
  }).catch((error) => {
    console.log(error);
  });
})


const handleRegister = async () => {
  if(recName.value === username.value && recContact.value === Contact.value && recContactType.value === radio.value && password.value === '••••••••' && ifChange.value === false){
    ElMessage({
      message: '未修改信息',
      type: 'error',
      style: 'font-size:25px;font-weight:bold;',
      offset: 55,
      grouping:true
    })
    return;
  }
  // 验证联系方式是否同时填写
  if (!((Contact.value === '' && radio.value === '' || (Contact.value !== '' && radio.value !== '')))) {
    ElMessage({
      message: '请同时填写联系方式和联系方式类型或不填',
      type: 'error',
      style: 'font-size:25px;font-weight:bold;',
      center: true,
      offset: 55
    })
    return
  }

  // 验证联系方式格式是否正确
  if(radio.value === 0){
    const wxReg = /^[a-zA-Z][a-zA-Z\d_-]{5,19}$/
    if(!wxReg.test(Contact.value)){
      ElMessage({
        message: '请输入正确格式的微信号',
        type: 'error',
        style: 'font-size:25px;font-weight:bold;',
        center: true,
        offset: 55
      })
      return
    }
  }
  else if(radio.value === 1){
    const qqReg = /^[1-9][0-9]{4,14}$/
    if(!qqReg.test(Contact.value)){
      ElMessage({
        message: '请输入正确格式的QQ号',
        type: 'error',
        style: 'font-size:25px;font-weight:bold;',
        center: true,
        offset: 55
      })
      return
    }
  }
  else if(radio.value === 2){
    const telReg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
    if(!telReg.test(Contact.value)){
      ElMessage({
        message: '请输入正确格式的手机号码',
        type: 'error',
        style: 'font-size:25px;font-weight:bold;',
        center: true,
        offset: 55
      })
      return
    }
  }

  formData.append("UName", username.value);
  formData.append("ProfilePhoto", image.value);
  if (password.value === '••••••••') {
    password.value = ''
  }
  formData.append("Password", password.value);
  formData.append("Contact", Contact.value);
  formData.append("ContactType", radio.value);

  try {
    const response = await axios.post('http://localhost:8080/users/modify', formData);
    if (response.status === 200) {
      password.value='••••••••'
      ifModified.value = true
      ElMessage({
        message: '修改成功',
        type: 'success',
        style: 'font-size:25px;font-weight:bold;',
        offset: 55,
        grouping:true
      })
      setTimeout(()=>{
        location.reload()
      },2000)
    } else {
      ElMessage({
        message: '修改失败',
        type: 'error',
        style: 'font-size:25px;font-weight:bold;',
        center: true,
        offset: 55,
        grouping:true
      })
    }
  } catch (error) {
    ElMessage({
      message: '修改失败',
      type: 'error',
      style: 'font-size:25px;font-weight:bold;',
      center: true,
      offset: 55,
      grouping:true
    })
  }
};

const passwordFocusIn = () => {
  if (password.value === '••••••••') {
    password.value = ''
  }
}
const passwordFoucusOut = () => {
  if (password.value === '') {
    password.value = '••••••••'
  }
}
const handleAvatarSuccess = (res, file) => {
  imageUrl.value = URL.createObjectURL(file.raw);
  formData.append("ProfilePhoto", file.raw);
};

const handleChange = (uploadFile) => {
  ifChange.value = true;
  imageUrl.value = URL.createObjectURL(uploadFile.raw)
  image.value = uploadFile.raw;
}
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    ElMessage({
      message: '上传头像图片只能是 JPG 格式!',
      type: 'error',
      style: 'font-size:25px;font-weight:bold;',
      offset: 55,
      grouping:true
    })
  }
  if (!isLt2M) {
    ElMessage({
      message: '上传头像图片大小不能超过 2MB!',
      type: 'error',
      style: 'font-size:25px;font-weight:bold;',
      offset: 55,
      grouping:true
    })
  }
  return isJPG && isLt2M;
};

const closeDialog = () =>{
  if(ifModified.value === true){
    location.reload();
  }
}
</script>

<template>
  <el-button @click="editHandle" class="changeBtn" color="#FFD466">修改信息</el-button>
  <el-dialog v-model="isEditVisible" @close="closeDialog" :width="420" center>
    <div class="register-content">
      <form @submit.prevent="handleRegister">
        <!-- 圆形图片上传 -->
        <div class="avatar-uploader-container">
          <el-upload
              class="avatar-uploader"
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handleChange"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" alt="">
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </div>
        <div class="form-group">
          <el-input type="text"
                    id="username"
                    v-model="username"
                    style="height: 40px; width : 300px; font-size: 16px;"
          >
            <template #prefix>
              <el-icon style="font-size: 24px;">
                <User/>
              </el-icon>
            </template>
          </el-input>
        </div>
        <div class="form-group">
          <el-input type="text"
                    disabled="true"
                    id="email"
                    v-model="email"
                    placeholder="请输入您的邮箱"
                    style="height: 40px; width : 300px; font-size: 16px;"
          >
            <template #prefix>
              <el-icon style="font-size: 24px;">
                <Message/>
              </el-icon>
            </template>
          </el-input>
        </div>
        <div class="form-group">
          <el-input id="password"
                    v-model="password"
                    @focusin="passwordFocusIn"
                    @focusout="passwordFoucusOut"
                    style="height: 40px; width : 300px; font-size: 16px;"
          >
            <template #prefix>
              <el-icon style="font-size: 24px;">
                <Lock/>
              </el-icon>
            </template>
          </el-input>
        </div>

        <div class="form-group">
          <el-input type="text"
                    id="Contact"
                    v-model="Contact"
                    placeholder="请输入您的联系方式"
                    style="height: 40px; width : 300px; font-size: 16px;"
          >
            <template #prefix>
              <el-icon style="font-size: 24px;">
                <ChatRound/>
              </el-icon>
            </template>
          </el-input>
        </div>
        <div class="form-group">
          <el-radio-group v-model="radio" class="custom-radio-group">
            <el-radio :label="0">微信</el-radio>
            <el-radio :label="1">QQ</el-radio>
            <el-radio :label="2">电话</el-radio>
          </el-radio-group>
        </div>
        <div class="form-group">
          <button type="submit" class="submit-button">确认修改</button>
        </div>
      </form>
    </div>
  </el-dialog>
</template>

<style scoped>
.changeBtn {
  width: 100px;
  height: 50px;
  font-size: 18px;
  font-weight: bold;
  color: white;
  border-radius: 15px;
  margin-top: 45px;
  margin-left: auto;
  margin-right: 70px;
}

.changeBtn:hover {
  color: white;
}

.register-content {
  background: white;
  display: flex;
  justify-content: center;

}

.form-group {
  margin-bottom: 20px;
  display: flex;
  justify-content: center;
}

label {
  display: block;
  margin-bottom: 5px;
  color: #333;
}

.el-input {
  width: 100%;
}

.submit-button {
  font-weight: bold;
  display: flex;
  justify-content: center;
  width: 250px;
  height: 40px;
  padding: 10px;
  font-size: 15px;
  background-color: #FFD466;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  letter-spacing: 2px; /* 设置字符间的间距，这里设置为2px，可根据需要调整 */
}

.submit-button:hover {
  background-color: #FFB74D;
}

.error-message {
  color: red;
  text-align: center;
  margin-top: 10px;
}

.success-message {
  color: green;
  text-align: center;
  margin-top: 10px;
}

/* 自定义 radio 样式 */
.custom-radio-group {
  display: flex;
  justify-content: center;
}

/*头像样式*/
.avatar-uploader-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 20px;
  margin-top: 20px;
}

.avatar-uploader-container:focus {
  background-color: white;
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar {
  font-size: 28px;
  width: 150px;
  height: 150px;
  line-height: 140px; /* 垂直居中 */
  text-align: center;
  object-fit: cover;
}
</style>
